package biback.domain.common.service

import biback.domain._
import biback.domain.common._
import biback.domain.common.model.BranchLevel
import biback.utils.{DomainError, GeneralAlgebra}
import cats.Monad

class AddBranchService[F[_] : Monad]
(
  algebra: BranchAlgebra[F]
) extends GeneralAlgebra[F] {
  import algebra._
  import model.BranchLevel._
  def addBranch(ctx: TrnContext, rq: AddBranchRequest): ErrOrNoneF = {
    for {
      _ <- branch.notFound(rq.brcNo)
      u <- branch.found(rq.upBrcNo)
      _ <- assertF(u.level == BranchLevel.Superiors, IsNotSuperior)
      e <- branch.create(rq.brcNo, ctx, Branches, Some(rq.upBrcNo))
    } yield e
  }

  def addSuperior(ctx: TrnContext, rq: AddUpBranchRequest): ErrOrNoneF = {
    for {
      _ <- branch.notFound(rq.brcNo)
      s <- branch.foundHeadBranch()
      e <- branch.create(rq.brcNo, ctx, Superiors, Some(s.no))
    } yield e
  }

  def addHeadquarter(ctx: TrnContext, rq: AddUpBranchRequest): ErrOrNoneF = {
    for {
      _ <- branch.notFoundHeadBranch()
      e <- branch.create(rq.brcNo, ctx, Headquarter)
    } yield e
  }
}

case class AddBranchRequest
(
  brcNo: BranchNo,
  upBrcNo: BranchNo
)

case class AddUpBranchRequest
(
  brcNo: BranchNo
)

case object IsNotSuperior extends DomainError